import React, { useContext, useEffect, useState, useMemo } from 'react';
import { useNavigate } from 'react-router';
import moment from 'moment';
import { AntDesignOutlined, FilterOutlined, UserOutlined } from '@ant-design/icons';
import {
  Tag,
  Cascader,
  Button,
  Modal,
  Progress,
  Form,
  Input,
  Row,
  Col,
  Select,
  Avatar,
  Tooltip,
  Spin,
  Pagination
} from 'antd';
import { useTranslation } from 'react-i18next';

import SearchInputCom from '@src/components/SearchInputCom';
import WinningRateModal from '../WinningRateModal';

import { getMarkList, getMarkCity } from '@src/services/market';
import { formatTimeDifference, formatTimeHowLongAgo } from '@src/utils/dataHandlingFunc';
import { PublicDataStore } from '@src/store/PublicData/Provider.js';

import styles from './styles.module.less';

const { TextArea } = Input;

const MaretList = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { state } = useContext(PublicDataStore);

  const [getListLoading, setGetListLoading] = useState(false);
  const [marketData, setMarketData] = useState({
    tenders: [],
    total: 0
  });
  const [marketListPage, setMarketListPage] = useState(1);
  const [filterKeys, setFilterKeys] = useState({
    Server: [''],
    Market: [''],
  });
  const [winningRateVisible, setWinningRateVisible] = useState(false);
  const [requirementModalVisible, setRequirementModalVisible] = useState(false);
  const [filterSearchValue, setFilterSearchValue] = useState('');
  const [filterBusinessId, setFilterBusinessId] = useState('');
  const [filterCityId, setFilterCityId] = useState('');
  const [cityList, setCityList] = useState([]);

  useEffect(() => {
    onLoad({});
    onGteCity()
  }, [])

  const onLoad = async ({
    page = marketListPage,
    search_keys = filterSearchValue,
    business_id = filterBusinessId,
    city_id = filterCityId
  }) => {
    setGetListLoading(true);
    const res = await getMarkList({
      page,
      search_keys,
      business_id,
      city_id
    });

    if (!res) return;

    setGetListLoading(false);
    setMarketData(res);
  }

  const onGteCity = async () => {
    const res = await getMarkCity();

    if (!res) return;

    setCityList(res);
  }

  const onMarketListPageChange = (page) => {
    setMarketListPage(page);
    onLoad({
      page
    })
  }


  const onFilterChange = (type, tag, checked) => {
    setFilterKeys(old => {
      let newState = {
        ...old,
        [type]: checked ? [tag] : []
      }

      onLoad({
        business_id: newState.Server[0] || '',
        city_id: newState.Market[0] || ''
      });
      return newState
    });


  };

  const onSearch = (value) => {
    setFilterSearchValue(value);

    onLoad({
      search_keys: value
    });
  }

  const serverOption = useMemo(() => {
    let options = [];

    // 服务
    let serveOption = {
      label: 'Serve',
      value: 'Server',
      children: state.allBusiness.map(item => ({
        label: item.business_name,
        value: item.business_id
      }))
    };
    options.push(serveOption);

    // 城市
    let marketOption = {
      label: 'Market',
      value: 'Market',
    };

    let cityOption = {};

    cityList.forEach(item => {
      if (cityOption[item.country]) {
        cityOption[item.country].push(item)
      } else {
        cityOption[item.country] = [item]
      }
    });

    marketOption.children = Object.keys(cityOption).map(item => ({
      label: item,
      value: item,
      children: cityOption[item]
    }));

    options.push(marketOption);

    return options
  }, [state.allBusiness, cityList])

  return (
    <div className={styles.market_box}>
      <div className={styles.top_title}>
        {t('Search for benchmark news across the entire network to obtain massive business opportunities')}
      </div>
      <div className={styles.inquire_box}>
        <div className={styles.search_box}>
          <div style={{ width: '100%' }}>
            <SearchInputCom submitFun={onSearch} />
          </div>
        </div>
      </div>
      <div className={styles.filter_box} >
        {
          serverOption.map(_server => (
            <div className={styles.row_box} key={_server.label}>
              <span className={styles.row_label}>{t(_server.label)}：</span>
              <div className={styles.filter_content}>
                {
                  _server.children?.map(_tag => {
                    if (_tag.children) {
                      return (
                        <div className={styles.row_two_box} key={_tag.label}>
                          <span className={styles.row_two_label}>{t(_tag.label)}：</span>
                          <div className={styles.filter_content}>
                            {
                              _server.label === 'Serve' ? _tag.children?.map(_tagTwo => (
                                <Tag.CheckableTag
                                  key={_tagTwo.label}
                                  checked={filterKeys[_server.value].indexOf(_tagTwo.value) > -1}
                                  onChange={(checked) => onFilterChange(_server.value, _tagTwo.value, checked)}
                                >
                                  {t(_tagTwo.label)}
                                </Tag.CheckableTag>
                              ))
                                : _tag.children?.map(_tagTwo => (
                                  <Tag.CheckableTag
                                    key={_tagTwo.city_id}
                                    checked={filterKeys[_server.value].indexOf(_tagTwo.city_id) > -1}
                                    onChange={(checked) => onFilterChange(_server.value, _tagTwo.city_id, checked)}
                                  >
                                    {t(_tagTwo?.[sessionStorage.getItem('ai_lang')])}
                                  </Tag.CheckableTag>
                                ))
                            }
                          </div>
                        </div>
                      )
                    }

                    return (
                      <>
                        {
                          _server.label === 'Serve' ? (
                            <Tag.CheckableTag
                              key={_tag.label}
                              checked={filterKeys[_server.value].indexOf(_tag.value) > -1}
                              onChange={(checked) => onFilterChange(_server.value, _tag.value, checked)}
                            >
                              {t(_tag.label)}
                            </Tag.CheckableTag>
                          ) : (
                            <Tag.CheckableTag
                              key={_tag.label}
                              checked={filterKeys[_server.value].indexOf(_tag.city_id) > -1}
                              onChange={(checked) => onFilterChange(_server.value, _tag.city_id, checked)}
                            >
                              {t(_tag.label)}
                            </Tag.CheckableTag>
                          )
                        }
                      </>
                    )
                  })
                }
              </div>
            </div>
          ))
        }
      </div>

      <div className={styles.card_box}>
        <div className={styles.first_card_box} onClick={() => navigate('/market/0')}>
          <div className={styles.top_box}>
            <div className={styles.time}>2024-07-17</div>
            <div className={styles.price}>$5000-9000</div>
          </div>
          <div className={styles.name}>Bandwidth Requirement for 150M Pipeline from Dubai to Frankfurt</div>
          <div className={styles.describe}>
            Design a 150M bandwidth pipeline to connect Dubai and Frankfurt for high-speed data transmission. The pipeline needs to traverse different terrains and water bodies, including underwater, deserts, and urban areas. The system should possess high-speed data transmission capabilities, secure encryption mechanisms, fault recovery features...
          </div>
          <ul className={styles.info_box}>
            <li>Expires In： 9d 8h</li>
            <li>Qualification Requirements： 3C</li>
            <li>Number of Bids Placed： 3</li>
            <li>Earnest Money Deposited： $300</li>
          </ul>
          <div className={styles.more_box}>{'Read More >>'}</div>
          <div className={styles.apply}>
            <Button
              type='primary'
              onClick={(e) => {
                e.stopPropagation();
                setWinningRateVisible(true);
              }}
            >{t('Apply for Bidding')}</Button>
          </div>
        </div>
      </div>
      <Spin spinning={getListLoading}>
        <div className={styles.card_list_box}>
          {
            marketData?.tenders?.map(item => (
              <div className={styles.item_box} onClick={() => navigate(`/market/${item.tender_id}`)} key={item.tender_id}>
                <div className={styles.top}>
                  <div className={styles.time}>
                    {moment(item.expiration_date).format('YYYY/MM/DD')}
                  </div>
                  <div className={styles.countdown}>
                    {t('Expiration time')}：{t(formatTimeDifference(item.expiration_date))}
                  </div>
                </div>
                <div className={styles.name}>
                  {item.title}
                </div>
                <div className={styles.desc}>
                  {item.description}
                </div>
                <div className={styles.bottom_box}>
                  <div className={styles.tag_box}>
                    <Tag color="#7d68ef">{state.allBusiness?.find(_business => _business.business_id === item.business_id)?.business_name || ''}</Tag>
                  </div>
                  <div className={styles.more}>
                    {`预算：￥${item.min_budget || 0}-${item.max_budget || 0} /${item.unit || '年'}`}
                  </div>
                </div>

                <div>
                  <div className={styles.avatar_span}>
                    <span style={{ color: '#999' }}>{item.create_time ? formatTimeHowLongAgo(item.create_time) : ''}</span>
                    <span style={{ float: "right" }}>
                      <Avatar.Group
                        size="small"
                        max={{
                          count: 2,
                          style: { color: '#f56a00', backgroundColor: '#fde3cf', cursor: 'pointer' },
                          popover: { trigger: 'click' },
                        }}
                      >
                        {
                          item?.bid?.map((bid, bidIdx) => (
                            <Tooltip title={bid?.comapny?.company_name} placement="top" key={bidIdx}>
                              <Avatar src={bid?.comapny?.logo_path} />
                            </Tooltip>
                          ))
                        }
                      </Avatar.Group>
                    </span>

                  </div>

                </div>

              </div>
            ))
          }
          {
            [...Array(3)].map((_, index) => (
              <i key={index} style={{ width: '32%' }} />
            ))
          }
        </div>
      </Spin>
      <div className={styles.page_box}>
        <Pagination current={marketListPage} total={marketData.total} onChange={onMarketListPageChange} pageSize={9} />
      </div>


      <WinningRateModal winningRateVisible={winningRateVisible} setWinningRateVisible={setWinningRateVisible} />

      <div className={styles.create_requirement_box}>
        <div className={styles.desc}>
          {t('Simply complete these 3 easy steps to connect with industry-leading network service providers from around the world')}
          <span>
            {t('To view the steps.')}
          </span>
        </div>

        <Button type='primary' onClick={() => setRequirementModalVisible(true)}>{t('Publication of requirements')}</Button>
      </div>

      <Modal
        open={requirementModalVisible}
        footer={null}
        onCancel={() => setRequirementModalVisible(false)}
        style={{ minWidth: 650 }}
      >
        <div className={styles.requirement_modal_box}>
          <div className={styles.title}>{t('Create a requirement')}</div>
          <div className={styles.form_box}>
            <Form layout="vertical">
              <Form.Item label='Title' name="title" required>
                <Input name="title" />
              </Form.Item>
              <Form.Item label='Description' name="description" required>
                <TextArea name="description" />
              </Form.Item>
              <Form.Item label='Deadline' name="deadline" required>
                <Input name="deadline" placeholder='July 30, 2024' />
              </Form.Item>
              <Form.Item label='Service' name="service" required>
                <Input name="service" placeholder='DIA' />
              </Form.Item>
              <Form.Item label='Markets' name="markets" required>
                <Input name="markets" placeholder='Hong Kong,Frankfurt' />
              </Form.Item>
              <Row justify='space-between'>
                <Col span={5}>
                  <Form.Item label='From' name="from" required>
                    <Select name="from" placeholder='Singapore'></Select>
                  </Form.Item>
                </Col>
                <Col span={5}>
                  <Form.Item label='To' name="To" required>
                    <Select name="To" placeholder='Hong Kong'></Select>
                  </Form.Item>
                </Col>
                <Col span={5}>
                  <Form.Item label='Contract Period' name="period" required>
                    <Select name="period" placeholder='6'></Select>
                  </Form.Item>
                </Col>
                <Col span={5}>
                  <Form.Item label='Bandwidth' name="Bandwidth" required>
                    <Select name="Bandwidth" placeholder='50'></Select>
                  </Form.Item>
                </Col>
              </Row>
              <div className={styles.footer_box}>
                <Button type='primary' onClick={() => setRequirementModalVisible(false)}>{t('Create')}</Button>
              </div>
            </Form>
          </div>
        </div>
      </Modal>
    </div>
  )
};

export default MaretList;